package com.ft.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ft.dao.NongsukeOrderDao;
import com.ft.domain.Nongsuke;
import com.ft.domain.NongsukeOrder;
import com.ft.domain.User;
import com.ft.service.INongsukeOrderService;
import com.ft.utils.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class NongsukeOrderServiceImpl extends ServiceImpl<NongsukeOrderDao, NongsukeOrder> implements INongsukeOrderService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private NongsukeOrderDao nongsukeOrderDao;
    /**
     * 增加订单
     *
     * @param order
     * @return
     * @throws IllegalAccessException
     */
    @Override
    public int addOrder(NongsukeOrder order) throws IllegalAccessException {
        int i = nongsukeOrderDao.addOrder(order);
        if (i == 1) {
            //1.将订单存入助农服务订单集合中
            String id = String.valueOf(order.getId());
            redisTemplate.opsForZSet().add("nongsukeorderId", id, 0);
            //2.创建订单hash表
            String orderKey1 = "nongsukeorder:" + order.getId();
            Map<String, Object> stringObjectMap = ObjectUtils.objectToMap(order);
            redisTemplate.opsForHash().putAll(orderKey1, stringObjectMap);
            //3.将订单存入自己发的订单表中
            redisTemplate.opsForSet().add(order.getIssuseuserid() + ":nongsukeorderid:", "" + id);
            return 1;
        }
        return 0;
    }

    /**
     * 获取订单所有字段数据
     *
     * @param id
     * @return
     */
    @Override
    public NongsukeOrder getOrder(Long id) {
        NongsukeOrder nongsukeOrder = nongsukeOrderDao.selectOrder(id);
        return nongsukeOrder;
    }

    /**
     * 修改订单状态
     *
     * @param state
     * @param id
     * @param id
     * @return
     */
    @Override
    public int updataOrderState(int state, String id) {
        int i = nongsukeOrderDao.updataOrderState(state, id);
        if (i == 1) {
            //修改数据库中的数据
            String key = "nongsukeorder:" + id;
            //将订单类型zet集合中的对应订单id的score值加1
            redisTemplate.opsForZSet().incrementScore("nongsukeorderId", id, 1);
            //修改订单hash表state状态
            redisTemplate.opsForHash().delete(key, state);
            redisTemplate.opsForHash().put(key, "state", 1);
            //更新订单时间
            redisTemplate.opsForHash().delete(key, "updateTime");
            String time = nongsukeOrderDao.getupdateTime(Long.valueOf(id));
            redisTemplate.opsForHash().put(key, "updateTime", time);
            return 1;
        }
        return 0;
    }

    @Override
    public int updateOrderRefund(String orderid, int state) {
        return 0;
    }

}
